package com.shadow.demo.common.util.ip;

import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Calendar;
import java.util.Enumeration;

@Slf4j
public final class IPUtils {

    private IPUtils() {
    }

    /**
     * 获取本机机器名
     * */
    public static String getLocalHostName() {
        try {
            return InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
            log.error("获取本机机器名异常", e);
        }
        return null;
    }

    /**
     * 获取本地ip
     * */
    public static AppAddressInfo getAppAddressInfo() throws SocketException {
        StringBuilder ipAddress = new StringBuilder();
        Boolean isFirst = Boolean.TRUE;
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface networkInterface = networkInterfaces.nextElement();
            Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
            while (inetAddresses.hasMoreElements()) {
                InetAddress inetAddress = inetAddresses.nextElement();
                if (!inetAddress.isLoopbackAddress() &&
                        !inetAddress.isLinkLocalAddress()
                        && inetAddress.isSiteLocalAddress()
                ) {
                    String hostAddress = inetAddress.getHostAddress();
                    if (Boolean.FALSE.equals(isFirst)) {
                        ipAddress.append(",");
                    }
                    ipAddress.append(hostAddress);
                    isFirst = Boolean.FALSE;
                }
            }
        }
        AppAddressInfo appAddressInfo = new AppAddressInfo()
                .setMachineName(getLocalHostName())
                .setIpAddress(ipAddress.toString())
                .setAddDate(Calendar.getInstance().getTime());
        if (log.isDebugEnabled()) {
            log.debug("ip is : {}", appAddressInfo);
        }
        return appAddressInfo;
    }

    public static void main(String[] args) {
        try {
            AppAddressInfo appAddressInfo = getAppAddressInfo();
            log.info("ip is : {}", appAddressInfo);
        } catch (Exception e) {
           log.error("An exception occurred", e);
        }
    }
}
